import { createApp } from 'vue'
import App from './App.vue'
import { normalRouter, managementRouter, globalRouter } from '@/router'
import store from '@/store'
import config from '@/config'
import axios from 'axios'
import Cookies from 'js-cookie'
import '@/assets/icon/style.css'
import '@/assets/style/variables.less'
import '@/assets/style/antd_custom.less'
import 'ant-design-vue/lib/message/style/index.css'
import 'ant-design-vue/lib/modal/style/index.css'
import message from 'ant-design-vue/lib/message/index.js'
import Modal from 'ant-design-vue/lib/modal/index.js'
import { setupPermissionDirective } from '@/directives/Permission.js'
import { setupVirtualScrollDirective } from '@/directives/VirtualScroll.js'
const app = createApp(App)
const token = Cookies.get(config.COOKIE_KEY) || config.TEMP_TOKEN
if (token) {
  axios
    .get(config.API_BASE + '/User/GetLoginUserInfo', {
      headers: {
        authorization: 'Bearer ' + token
      }
    })
    .then(({ data }) => {
      if (data.data.isManager || data.data.isHRBP) {
        // 既有管理又有销售权限的根据上次选择进入对应视图，默认进入普通视图
        if (data.data.roleInfo.includes(11)) {
          if (Cookies.get('USER-VIEW') === '1') {
            app.use(managementRouter)
          } else if (Cookies.get('USER-VIEW') === '2') {
            app.use(normalRouter)
          } else {
            app.use(normalRouter)
            Cookies.set('USER-VIEW', '2', { expires: 365 })
          }
        } else {
          // 没有销售权限的，直接进入管理视图
          app.use(managementRouter)
          Cookies.set('USER-VIEW', '1', { expires: 365 })
        }
        // 如果是BusinessPersonnel角色，默认只有管理视图
      } else if (data.data.roleInfo.includes(42) && !data.data.isManager) {
        app.use(managementRouter)
        Cookies.set('USER-VIEW', '1', { expires: 365 })
      } else if (data.data.roleInfo.includes(11)) {
        // 其他情况且具有销售角色进入普通视图
        app.use(normalRouter)
        Cookies.set('USER-VIEW', '2', { expires: 365 })
      } else {
        app.use(globalRouter)
      }
      store.commit('user/setToken', token)
      store.commit('user/setUserInfo', data.data)
      app.use(store)
      app.provide('Feedback', { message, Modal })
      setupPermissionDirective(app)
      setupVirtualScrollDirective(app)
      app.mount('#app')
    })
    .catch(() => {
      message.error('Authentication failed, Please re-login.')
      setTimeout(() => {
        window.location = config.LOGIN_URL + window.location
      }, 3000)
    })
} else {
  window.location = config.LOGIN_URL + window.location
}
